# coding: utf-8
from typing import Callable

from PySide6.QtCore import QObject, Signal
from qeventmanager.handler import ResponseHandler, RequestHandler
from qeventmanager.que_thread import QueThread


class QManager(QObject):
    started = Signal()
    finished = Signal()
    failed = Signal(object)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.que_thread = QueThread(self)

        self.que_thread.result.connect(self.on_result)
        self.que_thread.failed.connect(self.failed)
        self.que_thread.finished.connect(self.finished)
        self.que_thread.started.connect(self.started)

    def on_result(self, response: ResponseHandler):
        if response.slot:
            response.slot(response.result)

    def addTask(self, func: Callable, *args, slot: Callable = None, **kwargs):
        """
        添加任务
        :param func:
        :param args:
        :param slot:
        :param kwargs:
        :return:
        """
        request = RequestHandler(func, *args, **kwargs, slot=slot)
        self.que_thread.addTask(request)


qmanager = QManager()
